package mvv.learn.spring.dao;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;

import org.springframework.beans.factory.annotation.Autowired;

/**
 * @author Manh Vu
 */
public class BaseDaoImpl<T, ID extends Serializable> implements BaseDao<T, ID> {
	@Autowired
	private EntityManagerFactory entityManagerFactory;

	private Class<T> type;

	@SuppressWarnings("unchecked")
	public BaseDaoImpl() {
		Type t = getClass().getGenericSuperclass();
		ParameterizedType pt = (ParameterizedType) t;
		type = (Class<T>) pt.getActualTypeArguments()[0];
	}

	/** @author Manh Vu */
	@Override
	public <S extends T> S save(S entity) {
		// TODO Auto-generated method stub
		return null;
	}

	/** @author Manh Vu */
	@Override
	public <S extends T> Iterable<S> save(Iterable<S> entities) {
		// TODO Auto-generated method stub
		return null;
	}

	/** @author Manh Vu */
	@Override
	public T findOne(ID id) {
		return getSession().find(type, id);
	}

	/** @author Manh Vu */
	@Override
	public boolean exists(ID id) {
		// TODO Auto-generated method stub
		return false;
	}

	/** @author Manh Vu */
	@SuppressWarnings("unchecked")
	@Override
	public Iterable<T> findAll() {
		String hql = "Select t From " + type.getSimpleName() + " t";
		Query query = getSession().createQuery(hql);
		return query.getResultList();
	}

	/** @author Manh Vu */
	@Override
	public Iterable<T> findAll(Iterable<ID> ids) {
		// TODO Auto-generated method stub
		return null;
	}

	/** @author Manh Vu */
	@Override
	public long count() {
		// TODO Auto-generated method stub
		return 0;
	}

	/** @author Manh Vu */
	@Override
	public void delete(ID id) {
		delete(findOne(id));
	}

	/** @author Manh Vu */
	@Override
	public void delete(T entity) {
		getSession().remove(entity);
	}

	/** @author Manh Vu */
	@Override
	public void delete(Iterable<? extends T> entities) {
		// TODO Auto-generated method stub

	}

	/** @author Manh Vu */
	@Override
	public void deleteAll() {
		// TODO Auto-generated method stub

	}

	/**
	 * @return current session
	 * @author Manh Vu
	 */
	public EntityManager getSession() {
		return entityManagerFactory.createEntityManager();
	}

}
